#include "ds1302.h"


//DS1302写入和读取时分秒的地址命令   秒分时日月周年
unsigned char code Read_RTC_CMD[7] = { 0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
unsigned char code Write_RTC_CMD[7] = { 0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};

//初始化2020年9月14日星期一 8点00分00秒存储顺序是秒分时日月周年，存储格式是用BCD码
unsigned char time[8] = { 0x00,0x00,0x08,0x14,0x09,0x02,0x20,0x00 };

//dat BCD码 addr 寄存器地址 或命令字节
void DS1302Write(unsigned char addr, unsigned char dat)
{
	CE = 0;//初始化CE为低
	SCLK = 0;//初始化SCLK为低
	CE = 1;//CE拉高，使能芯片DS1302
	DS1302WriteByte(addr);//写入命令字节
	DS1302WriteByte(dat);//写入数据
	CE = 0;//传送结束
}

unsigned char DS1302Read(unsigned char addr)
{
	unsigned char dat = 0;
	CE = 0;//初始化CE为低
	SCLK = 0;//初始化SCLK为低
	CE = 1;//CE拉高，使能芯片DS1302
	DS1302WriteByte(addr);//写入命令字节
	dat = DS1302ReadByte();
	CE = 0;//读取结束
	DS1302_IO = 0;
	return dat;
}

void DS1302Init()
{
	unsigned char i;
	DS1302Write(0x8E,0x00);//关闭写保护
	for (i = 0; i < 7; i++)
	{
		DS1302Write(Write_RTC_CMD[i],time[i]);
	}
	DS1302Write(0x8E,0x80);//打开写保护，只读
}

void DS1302ReadTimer()
{
	unsigned char i;
	for (i = 0; i < 7; i++)
	{
		time[i] = DS1302Read(Read_RTC_CMD[i]);
	}
}

//Burst模式 读写时注意：一个字节的命令字，8个字节的数据 共72个脉冲
void DS1302BurstWrite()
{
	unsigned char i;
	CE = 1;
	DS1302WriteByte(BURST_WRITE);//0xBE  命令 是Burst模式进行多字节写 是需要写8个字节
	for (i = 0; i < 8; i++)
	{
		DS1302WriteByte(time[i]);
	}
	CE = 0;
}

void DS1302BurstRead(unsigned char *buf)
{
	unsigned char i;
	CE = 1;//芯片使能
	DS1302WriteByte(BURST_READ);//0xBF Burst模式多字节读
	for (i = 0; i < 8; i++)
	{
		buf[i] = DS1302ReadByte();
	}
	DS1302_IO = 0;
	CE = 0;
}

void DS1302BurstInit()
{
	unsigned char state;
	state = DS1302Read(0x81);
	if ((state & 0x80) != 0)
	{
		DS1302Write(0x8E,0x00);//关闭写保护
		DS1302BurstWrite();
		DS1302Write(0x8E,0x80);//打开写保护，只读	
	}
}